from django.db.models import Q
from base.models.travelSpot import travelSport
from base.serializers import travelSportSerializer
from django.http import JsonResponse, HttpResponse
from django.core.paginator import Paginator
from base.models.MyUserCommend import MyUserCommend
from base.serializers import MyUserCommendSerializer
# 序列化 travelSport


def getMyUserCommentCount(request):
    obj = MyUserCommend.objects.all()
    p = Paginator(obj, 6)

    return HttpResponse(p.count)


def getMyUserComment(request):
    pageSize = request.GET['pageSize']
    pageNum = request.GET['pageNum']

    obj = MyUserCommend.objects.all()
    ObjPaginator = Paginator(obj, pageSize)
    resList = MyUserCommendSerializer(
        ObjPaginator.get_page(pageNum).object_list, many=True)

    spotList = []
    for item in ObjPaginator.get_page(pageNum):
        tid = item.spot.tid
        print(tid)
        tmp = travelSport.objects.get(tid=tid)
        serializer = travelSportSerializer(tmp)
        spotList.append(serializer.data)

    finalList = []
    for x, y in zip(spotList, resList.data):
        finalList.append({
            'spot': x,
            'comment': y
        })
    return JsonResponse(finalList, safe=False)


def getSpotTidBySearch(request):
    content = request.GET['content']
    q = Q(spot_name__contains=content)
    spotList = travelSport.objects.filter(q)

    return JsonResponse(travelSportSerializer(spotList, many=True).data, safe=False)


def getTidInfo(request):
    tid = request.GET['tid']
    print(tid)
    spot = travelSport.objects.get(tid=tid)
    serializer = travelSportSerializer(spot)

    return JsonResponse(serializer.data, safe=False)


def getSportPageNum(request):
    obj = travelSport.objects.all()
    p = Paginator(obj, 12)

    return HttpResponse(p.num_pages)


def getSportByPage(request):
    pageSize = request.GET['pageSize']
    pageNum = request.GET['pageNum']

    obj = travelSport.objects.all()
    ObjPaginator = Paginator(obj, pageSize)
    resList = travelSportSerializer(
        ObjPaginator.get_page(pageNum).object_list, many=True)

    return JsonResponse(resList.data, safe=False)
